package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type LogMedService struct {
	repo repository.LogMedRepository
}

func NewLogMedService(repo repository.LogMedRepository) *LogMedService {
	return &LogMedService{repo: repo}
}

func (s *LogMedService) CreateLog(c *gin.Context) {
	var log model.LogMed
	if err := c.ShouldBindJSON(&log); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Create(&log); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, log)
}

func (s *LogMedService) GetLogByID(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	log, err := s.repo.GetByID(int64(idUint))
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, log)
}

func (s *LogMedService) ListLogsByApiCode(c *gin.Context) {
	apiCode := c.Param("apiCode")
	logs, err := s.repo.ListByApiCode(apiCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, logs)
}

func (s *LogMedService) ListLogsByHospital(c *gin.Context) {
	hospitalCode := c.Param("hospitalCode")
	logs, err := s.repo.ListByHospital(hospitalCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, logs)
}

func (s *LogMedService) DeleteLog(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	if err := s.repo.Delete(int64(idUint)); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}
